package com.xnfh.field.ui.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.view.OptionsPickerView
import com.bigkoo.pickerview.view.TimePickerView
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.interfaces.OnConfirmListener
import com.xnfh.common.bean.CropBean
import com.xnfh.common.bean.FieldDetailBean
import com.xnfh.field.R
import com.xnfh.field.databinding.ActivityFieldEditorLayoutBinding
import com.xnfh.field.viewmodel.FieldEditorViewModel
import com.xnfh.framework.base.BaseActivity
import com.xnfh.framework.base.BaseStateObserver
import com.xnfh.framework.ext.getDateYMD
import com.xnfh.framework.ext.getDateYMD_CN

/**
 * @Description:地块编辑、轮作
 * @Author: ziheng
 * @CreateDate: 2023/11/30 10:14
 * @UpdateUser: ziheng
 * @UpdateDate: 2023/11/30 10:14
 * @UpdateRemark: 更新说明
 */
class FieldEditorActivity : BaseActivity<ActivityFieldEditorLayoutBinding>(), View.OnClickListener {
    override fun getLayoutID(): Int = R.layout.activity_field_editor_layout

    companion object {
        const val REQUEST_CODE = 1002
        const val RESPONSE_CODE = 10002
        const val INTENT_TAG = "tagV" // 0编辑 1轮作
        fun start(context: Activity, bundle: Bundle? = null, requestCode: Int) {
            val intent = Intent(context, FieldEditorActivity::class.java)
            if (bundle != null) {
                intent.putExtra("bundle", bundle)
            }
            context.startActivityForResult(intent, requestCode)
        }
    }

    private var viewModel: FieldEditorViewModel? = null

    //选择作物pickerview
    lateinit var pickerBuilder: OptionsPickerView<CropBean>

    //作物id
    private var cropId: String? = null

    //种植时间
    private var time: Long? = null

    //选择时间pickerview
    lateinit var timePicker: TimePickerView
    private var data: FieldDetailBean? = null
    private var tag = 1
    override fun init(savedInstanceState: Bundle?) {
        val bundleExtra = intent.getBundleExtra("bundle")
        data = bundleExtra?.getSerializable("data") as FieldDetailBean
        cropId = data?.plantCropId
        tag = bundleExtra.getInt(INTENT_TAG, 1)
        mBind.fieldEditorTitle.headerTitleTxt.text = if (tag == 0) {
            getString(R.string.editor_field)
        } else {
            getString(R.string.str_lunzuo)
        }
        //编辑的时候，才展示右上角删除 和时间选择
        if (tag == 0) {
            mBind.fieldEditorTitle.rightTxt.visibility = View.VISIBLE
            mBind.fieldEditorTitle.rightTxt.text = getString(R.string.delete_field)
            mBind.fieldEditorTitle.rightTxt.setOnClickListener(this)
        }else{
            mBind.popEnclosureDknameEdit.isEnabled = false
            mBind.popEnclosureZztimeButton.setOnClickListener(this)
        }
        mBind.popEnclosureDknameButton.setOnClickListener(this)
        mBind.popEnclosureCancle.setOnClickListener(this)
        mBind.popEnclosureSure.setOnClickListener(this)

        mBind.popEnclosureDknameEdit.setText(data?.fieldName)
        mBind.popEnclosureDknameButton.text = data?.plantCropName
        mBind.popEnclosureZztimeButton.text = data?.startTime
        mBind.fieldEditorAddressValue.text = data?.address
    }

    override fun observe() {
        viewModel = FieldEditorViewModel()
        viewModel?.cropList?.observe(this, object : BaseStateObserver<List<CropBean>>(null) {
            override fun getRespDataSuccess(it: List<CropBean>) {
                super.getRespDataSuccess(it)
                if (it.isEmpty()) return
                if (!this@FieldEditorActivity::pickerBuilder.isInitialized) {
                    pickerBuilder = OptionsPickerBuilder(
                        this@FieldEditorActivity
                    ) { options1, options2, options3, v ->
                        //展示选中的作物
                        mBind.popEnclosureDknameButton.text = it[options1].scName
                        //存储作物id，保存地块的时候使用
                        cropId = it[options1].dautoid
                    }
                        .setTitleText(getString(com.xnfh.framework.R.string.pop_filed_zw))
                        .setTextColorCenter(Color.BLACK)
                        .setContentTextSize(20)
                        .build()
                }
                pickerBuilder.setPicker(it)
                pickerBuilder.show()
            }
        })
        viewModel?.removeField?.observe(this, object : BaseStateObserver<Any>(null) {
            override fun getRespDataSuccess(it: Any) {
                super.getRespDataSuccess(it)
                setResult(RESPONSE_CODE)
                finish()
            }
        })
    }

    override fun onClick(v: View?) {
        when (v) {
            mBind.popEnclosureDknameButton -> {
                //未初始化先初始化，初始化了之后，下次点击可以直接展示
                if (!this::pickerBuilder.isInitialized) {
                    viewModel?.requestCropList()
                } else {
                    pickerBuilder.show()
                }
            }

            mBind.popEnclosureZztimeButton -> {
                showTimePicker()
            }

            mBind.popEnclosureCancle -> {
                finish()
            }

            mBind.fieldEditorTitle.rightTxt -> {
                XPopup.Builder(this).asConfirm(
                    getString(R.string.str_ts),
                    getString(R.string.tips_delete_field),
                    object : OnConfirmListener {
                        override fun onConfirm() {
                            viewModel?.requestRemoveFieldById(data?.fieldId)
                        }
                    }).show()
            }
            mBind.popEnclosureSure ->{
                if(tag == 0){
                    //编辑地块信息
                    viewModel?.requestEditField(data?.fieldId,cropId,mBind.popEnclosureDknameEdit.text.toString())
                }else{
                    val requestTime = if(time == null){
                        data?.startTime
                    }else{
                        time?.getDateYMD()
                    }
                    //轮作
                    viewModel?.requestLzField(data?.fieldId,cropId,requestTime)
                }
            }
        }
    }

    private fun showTimePicker() {
        if (!this::timePicker.isInitialized) {
            timePicker = TimePickerBuilder(
                this
            ) { date, v ->
                time = date?.time
                mBind.popEnclosureZztimeButton.text = date?.time?.getDateYMD_CN()
            }.build()
        }
        timePicker.show()
    }
}